//app.js
App({
  /**
   * 全局变量
   */
  globalData: {
    isGetSession: false, //是否请求用户
    //地址 
    //apiRootUrl: 'https://api.banmachewu.com/youweiapi/api',
    apiRootUrl: 'https://dev.banmachewu.com/youweiapi/api',
    apiImgUrl: 'https://dev.banmachewu.com/youweiapi/images/',
    //apiImgUrl: 'https://api.banmachewu.com/youweiapi/images/',
    //用户key缓存
    userInfoKey: 'userInfoKey',
    //用户信息
    userInfo: {
      OpenID: '', //微信openid
      WeChartUserID: 0, //微信用户id
      UserID: 0, //用户id
      UserName: '', //用户名称
      SessionKey: '', //用户过期key
      UnionID: 0, //UnionID
      UserMobile: '', //电话号码
      NickName: '', //微信用户昵称
      UserHead: '', //微信用户头像
      VehicleStatus: 0, //用户行驶证级别 0：新建 1：填写级别信息待审核  2：审核 3：驳回
      Sex: 0, //1男 2女 0未知
      CarGroupIds: [], //用户行驶证车型ID集合
      CardLevel: 0 //0-没有 1-普通卡 2-黑金卡
    },
    //自定义状态栏高度 --colorui 所以没有添加systemInfo
    CustomBar: 0,
    //状态栏高度 --colorui 所以没有添加systemInfo
    StatusBar: 0,
    //菜单按钮布局 --colorui 所以没有添加systemInfo
    Custom: {},
    //屏幕高度
    screenHeight: 0,
    //窗体高度
    windowHeitht: 0,
    //平台
    platform: "",
    //分享信息
    shareInfo: {
      title: "以车为媒，驰天下路，聚八方友。",
      path: "/pages/index/index",
      imageUrl: "/images/banner.jpg"
    }
  },
  /**
   * 缓存用户信息
   * @param usr 用户信息
   */
  setUserInfo(usr) {
    let self = this;
    wx.setStorageSync(self.globalData.userInfoKey, JSON.stringify(usr));
    self.globalData.userInfo = usr;
  },
  /**
   * 小程序加载
   */
  onLaunch: function (options) {
    let self = this;
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        this.globalData.windowHeight = e.windowHeight;
        this.globalData.screenHeight = e.screenHeight;
        this.globalData.platform = e.platform;
        let capsule = wx.getMenuButtonBoundingClientRect();
        if (capsule) {
          this.globalData.Custom = capsule;
          this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
        } else {
          this.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    });
  },
  /**
   * 网络请求
   */
  httpRequest(opts) {
    let self = this;
    //请求处理
    if (opts.showLoading) {
      if (opts.method == "POST" || opts.method == "post") {
        //显示加载中
        wx.showLoading({
          title: '提交中...',
          mask: true
        });
      } else {
        //显示加载中
        wx.showLoading({
          title: '加载中...',
          mask: true
        });
      }
    }
    //添加headers
    if (opts.header) {} else {
      opts.header = {};
    }
    opts.header['Content-Type'] = 'application/json';
    //错误提示
    if (opts.fail) {} else {
      //如果错误添加错误日志
      opts.fail = function (res) {
        console.log(res);
      }
    }

    //微信小程序post参数必须,解析成字符串,官方标准解答
    if (opts.data) {
      if (opts.method == "POST" || opts.method == "post") {
        opts.data = JSON.stringify(opts.data);
      }
    }

    if (opts.complete) {} else {
      opts.complete = function (res) {
        if (opts.showLoading) {
          wx.hideLoading();
        }
      }
    }
    wx.request(opts);
  },
  /**
   * 添加微信用户
   */
  addWxUserInfo() {
    let self = this;
    //session_key 未过期，并且在本生命周期一直有效
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              self.checkSession().then(function () {
                console.log("用户授权成功");
                self.requestUser(res.userInfo);
              });
            },
            fail: res => {
              console.log("用户授权失败");
              wx.showToast({
                content: '请选择同意授权,否则影响后续操作', // 文字内容
                type: "none",
                duration: 1500
              });
            }
          });
        }
      }
    });

  },
  /**
   * 检测session_key是否过期
   * @param userinfo用户信息
   */
  checkSession() {
    let self = this;
    return new Promise(function (resolve, reject) {
      wx.checkSession({
        success(res) {
          //session_key 未过期，并且在本生命周期一直有效     
          resolve(res);
        },
        fail(res) {
          //session_key 过期 ，重新登陆
          self.getSession.then(resolve, function (rt) {
            reject(rt);
          });
        }
      });
    });
  },
  /**
   * 更新微信用户信息
   * @param userInfo 微信用户信息
   */
  requestUser(userInfo) {
    let self = this;
    let data = {
      "OpenID": self.globalData.userInfo.OpenID,
      "UnionID": self.globalData.userInfo.UnionID,
      "NickName": userInfo.nickName,
      "Sex": userInfo.gender,
      "City": userInfo.city,
      "Country": userInfo.country,
      "Province": userInfo.province,
      "Language": userInfo.language,
      "HeadImgUrl": userInfo.avatarUrl
    };
    return new Promise(function (resolve, reject) {
      self.httpRequest({
        url: self.globalData.apiRootUrl + '/WxUser/AddOrUpdate', // 目标服务器 url
        method: "POST",
        data: data,
        success(res) {
          if (res.data.status == 0) {
            self.globalData.userInfo.WeChartUserID = res.data.data.WeChartUserID; //微信用户id
            self.globalData.userInfo.NickName = res.data.data.NickName; //微信用户昵称
            self.globalData.userInfo.UserName = res.data.data.NickName; //微信用户昵称
            self.globalData.userInfo.UserHead = res.data.data.HeadImgUrl; //微信用户头像
            self.globalData.userInfo.Sex = userInfo.gender; //性别

            self.setUserInfo(self.globalData.userInfo);
            resolve();
          }
        },
        fail() {
          reject();
        }
      });

    });
  },
  /**
   * 获取session
   */
  getSession() {
    let self = this;
    return new Promise(function (resolve, reject) {
      if (self.globalData.isGetSession) {
        resolve();
        return;
      }

      //获取授权码
      wx.login({
        success: (lg) => {
          let url = self.globalData.apiRootUrl + '/WxMini/GetSession?authCode=' + lg.code;
          self.httpRequest({
            url: url,
            method: "GET",
            success: function (res) {
              if (res.data.status == 0) {
                if (res.data.data.CarGroupIds == null) {
                  res.data.data.CarGroupIds = [];
                }
                self.globalData.userInfo = res.data.data; //赋值用户信息
                self.setUserInfo(self.globalData.userInfo);
                self.globalData.isGetSession = true;
                resolve(res);
              } else {
                wx.showToast({
                  content: res.data.message, // 文字内容
                  type: "none",
                  duration: 1500
                });

                reject(res);
              }
            }
          });
        },
        fail: (err) => {
          self.globalData.isGetSession = true;
          wx.showToast({
            content: '请选择同意授权,否则影响后续操作', // 文字内容
            type: "none",
            duration: 1500
          });

          reject(err);
        }
      });
    });
  },
  /**
   * 是否可以添加评论
   */
  canAddComment: function (groupId) {
    let self = this;
    if (self.globalData.userInfo.UserID < 1) {
      wx.showModal({
        title: '提示',
        content: '请先注册认证，解锁体验完整功能',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/index/index',
            })
          }
        }
      });
      return false;
    } else {
      //判断是否注册相应车型
      for (let i = 0; i < self.globalData.userInfo.CarGroupIds.length; i++) {
        console.log(self.globalData.userInfo.CarGroupIds[i])
        if (self.globalData.userInfo.CarGroupIds[i] == groupId) {
          return true;
        }
      }

      wx.showModal({
        title: '提示',
        content: '请先认证车型，解锁体验完整功能',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/ucenter/drvlicense/drvlicense'
            });
          }
        }
      });
      return false;
    }
  }
})